from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from rest_framework.views import APIView
from goods.models import GoodsVisitCount
from users.models import User
from datetime import date, timedelta


class UserCountView(APIView):
    permission_classes = [IsAdminUser]
    #  用户总量统计
    def get(self, request):
        # 获取注册用户总数（普通用户）
        count = User.objects.filter(is_staff=False).count()
        return Response({"count":count})

class UserDayCountView(APIView):
    permission_classes = [IsAdminUser]
    # 当天注册用户总量统计
    def get(self, request):
        now_date = date.today()
        count = User.objects.filter(is_staff=False, date_joined__gte=now_date).count()
        return Response({"count":count})

class UserDayActiveCountView(APIView):
    permission_classes = [IsAdminUser]
    # 日活跃用户统计
    def get(self,request):
        now_date = date.today()
        count = User.objects.filter(is_staff=False, last_login__gte=now_date).count()
        return Response({"count": count})

class UserDayOrderCountView(APIView):
    """
        当天下单用户总量统计
    """
    # 权限指定
    permission_classes = [IsAdminUser]
    def get(self, request):
        # 获取当天日期
        now_date = date.today()
        # 获取当天下单用户总数（普通用户）  关联过滤查询 以订单表的数据作为用户表的查询条件
        users = User.objects.filter(is_staff=False, orders__create_time__gte=now_date)
        # 去重
        user = set(users)
        count = len(user)
        # 返回数量
        return Response({'count': count})

class UserDayMonthCountView(APIView):
    def get(self, request):
        # 获取当前日期
        now_date = date.today()
        # 获取一个月前日期
        start_date = now_date - timedelta(29)
        # 创建空列表保存每天的用户量
        date_list = []

        for i in range(30):
            # 循环遍历获取当天日期
            index_date = start_date + timedelta(days=i)
            # 指定下一天日期
            cur_date = start_date + timedelta(days=i + 1)
            # 查询条件是大于当前日期index_date，小于明天日期的用户cur_date，得到当天用户量
            count = User.objects.filter(date_joined__gte=index_date, date_joined__lt=cur_date).count()

            date_list.append({
                'count': count,
                'date': index_date
            })

            return Response(date_list)

class GoodsCountView(APIView):
    """
        商品分类访问量统计
    """
    # 权限指定
    permission_classes = [IsAdminUser]

    def get(self, request):
        # 获取当天日期
        now_date = date.today()
        # 获取商品分类访问量
        goods = GoodsVisitCount.objects.filter(date__gte=now_date)
        data_list=[]
        for good in goods:
            count = good.count
            # 获取关联分类对象的名字
            category = good.category.name
            data_list.append({"count":count,'category':category})
        # 返回数量
        return Response(data_list)

